package com.example.springboot2.service;

import com.example.springboot2.entity.Merchant;
import com.example.springboot2.repository.GoodsRepository;
import com.example.springboot2.repository.LaundryOrderRepository;
import com.example.springboot2.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 仪表板服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DashboardService {

    private final MerchantService merchantService;
    private final OrderRepository orderRepository;
    private final LaundryOrderRepository laundryOrderRepository;
    private final GoodsRepository goodsRepository;

    /**
     * 获取商家首页概览数据
     */
    public Map<String, Object> getMerchantOverview(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        
        Map<String, Object> overview = new HashMap<>();
        
        // 今日数据
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(LocalTime.MAX);
        
        // 订单统计
        long todayOrders = orderRepository.countByMerchantAndCreatedTimeBetween(merchant, todayStart, todayEnd);
        long totalOrders = orderRepository.countByMerchant(merchant);
        
        // 洗护订单统计
        long todayLaundryOrders = laundryOrderRepository.countByMerchantAndCreatedTimeBetween(merchant, todayStart, todayEnd);
        long totalLaundryOrders = laundryOrderRepository.countByMerchant(merchant);
        
        // 商品统计
        long totalGoods = goodsRepository.countByMerchant(merchant);
        
        // 销售额统计
        BigDecimal todayRevenue = orderRepository.sumActualAmountByMerchantAndCreatedTimeBetween(merchant, todayStart, todayEnd);
        BigDecimal todayLaundryRevenue = laundryOrderRepository.sumActualAmountByMerchantAndCreatedTimeBetween(merchant, todayStart, todayEnd);
        
        if (todayRevenue == null) todayRevenue = BigDecimal.ZERO;
        if (todayLaundryRevenue == null) todayLaundryRevenue = BigDecimal.ZERO;
        
        BigDecimal totalTodayRevenue = todayRevenue.add(todayLaundryRevenue);
        
        overview.put("todayOrders", todayOrders + todayLaundryOrders);
        overview.put("totalOrders", totalOrders + totalLaundryOrders);
        overview.put("todayRevenue", totalTodayRevenue);
        overview.put("totalGoods", totalGoods);
        overview.put("merchantInfo", merchant);
        
        return overview;
    }

    /**
     * 获取商家首页交易数据
     */
    public Map<String, Object> getMerchantTransaction(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        
        Map<String, Object> transaction = new HashMap<>();
        
        // 本月数据
        LocalDateTime monthStart = LocalDate.now().withDayOfMonth(1).atStartOfDay();
        LocalDateTime monthEnd = LocalDate.now().atTime(LocalTime.MAX);
        
        // 本月订单数量
        long monthOrders = orderRepository.countByMerchantAndCreatedTimeBetween(merchant, monthStart, monthEnd);
        long monthLaundryOrders = laundryOrderRepository.countByMerchantAndCreatedTimeBetween(merchant, monthStart, monthEnd);
        
        // 本月销售额
        BigDecimal monthRevenue = orderRepository.sumActualAmountByMerchantAndCreatedTimeBetween(merchant, monthStart, monthEnd);
        BigDecimal monthLaundryRevenue = laundryOrderRepository.sumActualAmountByMerchantAndCreatedTimeBetween(merchant, monthStart, monthEnd);
        
        if (monthRevenue == null) monthRevenue = BigDecimal.ZERO;
        if (monthLaundryRevenue == null) monthLaundryRevenue = BigDecimal.ZERO;
        
        transaction.put("monthOrders", monthOrders + monthLaundryOrders);
        transaction.put("monthRevenue", monthRevenue.add(monthLaundryRevenue));
        transaction.put("balance", merchant.getBalance());
        transaction.put("serviceRating", merchant.getServiceRating());
        
        return transaction;
    }

    /**
     * 获取商家首页商品数据
     */
    public Map<String, Object> getMerchantGoods(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        
        Map<String, Object> goods = new HashMap<>();
        
        // 商品统计
        long totalGoods = goodsRepository.countByMerchant(merchant);
        long onSaleGoods = goodsRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Goods.GoodsStatus.ON_SALE);
        long offSaleGoods = goodsRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Goods.GoodsStatus.OFF_SALE);
        long soldOutGoods = goodsRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Goods.GoodsStatus.SOLD_OUT);
        
        goods.put("totalGoods", totalGoods);
        goods.put("onSaleGoods", onSaleGoods);
        goods.put("offSaleGoods", offSaleGoods);
        goods.put("soldOutGoods", soldOutGoods);
        
        return goods;
    }

    /**
     * 获取商家首页订单数据
     */
    public Map<String, Object> getMerchantOrders(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        
        Map<String, Object> orders = new HashMap<>();
        
        // 普通订单统计
        long pendingOrders = orderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Order.OrderStatus.PENDING);
        long paidOrders = orderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Order.OrderStatus.PAID);
        long shippedOrders = orderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Order.OrderStatus.SHIPPED);
        
        // 洗护订单统计
        long pendingLaundryOrders = laundryOrderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.LaundryOrder.LaundryOrderStatus.PENDING);
        long acceptedLaundryOrders = laundryOrderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.LaundryOrder.LaundryOrderStatus.ACCEPTED);
        long inProcessLaundryOrders = laundryOrderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.LaundryOrder.LaundryOrderStatus.IN_PROCESS);
        
        orders.put("pendingOrders", pendingOrders + pendingLaundryOrders);
        orders.put("processingOrders", paidOrders + shippedOrders + acceptedLaundryOrders + inProcessLaundryOrders);
        orders.put("totalOrders", orderRepository.countByMerchant(merchant) + laundryOrderRepository.countByMerchant(merchant));
        
        return orders;
    }

    /**
     * 获取商家首页待处理事项
     */
    public Map<String, Object> getMerchantPendingTasks(Long userId) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        
        Map<String, Object> tasks = new HashMap<>();
        
        // 待处理订单
        long pendingOrders = orderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Order.OrderStatus.PENDING);
        long paidOrders = orderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Order.OrderStatus.PAID);
        
        // 待处理洗护订单
        long pendingLaundryOrders = laundryOrderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.LaundryOrder.LaundryOrderStatus.PENDING);
        long acceptedLaundryOrders = laundryOrderRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.LaundryOrder.LaundryOrderStatus.ACCEPTED);
        
        // 待上架商品
        long draftGoods = goodsRepository.countByMerchantAndStatus(merchant, 
                com.example.springboot2.entity.Goods.GoodsStatus.DRAFT);
        
        tasks.put("pendingPaymentOrders", pendingOrders);
        tasks.put("pendingShipmentOrders", paidOrders);
        tasks.put("pendingLaundryOrders", pendingLaundryOrders);
        tasks.put("acceptedLaundryOrders", acceptedLaundryOrders);
        tasks.put("draftGoods", draftGoods);
        
        return tasks;
    }

    /**
     * 获取商家首页销售趋势数据
     */
    public Map<String, Object> getMerchantSalesTrend(Long userId, String period) {
        Merchant merchant = merchantService.getMerchantInfo(userId);
        
        Map<String, Object> trend = new HashMap<>();
        
        // 根据period参数计算时间范围
        LocalDateTime startTime;
        LocalDateTime endTime = LocalDateTime.now();
        
        switch (period) {
            case "week":
                startTime = endTime.minusWeeks(1);
                break;
            case "month":
                startTime = endTime.minusMonths(1);
                break;
            case "year":
                startTime = endTime.minusYears(1);
                break;
            default:
                startTime = endTime.minusDays(7);
        }
        
        // 计算销售额
        BigDecimal revenue = orderRepository.sumActualAmountByMerchantAndCreatedTimeBetween(merchant, startTime, endTime);
        BigDecimal laundryRevenue = laundryOrderRepository.sumActualAmountByMerchantAndCreatedTimeBetween(merchant, startTime, endTime);
        
        if (revenue == null) revenue = BigDecimal.ZERO;
        if (laundryRevenue == null) laundryRevenue = BigDecimal.ZERO;
        
        // 计算订单数量
        long orderCount = orderRepository.countByMerchantAndCreatedTimeBetween(merchant, startTime, endTime);
        long laundryOrderCount = laundryOrderRepository.countByMerchantAndCreatedTimeBetween(merchant, startTime, endTime);
        
        trend.put("period", period);
        trend.put("revenue", revenue.add(laundryRevenue));
        trend.put("orderCount", orderCount + laundryOrderCount);
        trend.put("startTime", startTime);
        trend.put("endTime", endTime);
        
        return trend;
    }
}
